package com.waverider.promotion.biz.timetask;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.waverider.promotion.biz.manager.ItemManager;
import com.waverider.promotion.biz.manager.ShopManager;
import com.waverider.promotion.domain.PromotionDO;
import com.waverider.promotion.domain.ShopDO;
import com.waverider.promotion.enums.PromotionStatusEnum;
import com.waverider.promotion.model.BaseQueryModel;
import com.waverider.promotion.model.PromotionQueryModel;
import com.waverider.promotion.model.ResultModel;

/**
 * 
 * @author sihai
 * 
 */
public class PromotionTask {
	private static final Log logger = LogFactory.getLog(PromotionTask.class);

	private ItemManager itemManager;
	private ShopManager shopManager;

	private Map<Long, String> sessionKeyCache = new ConcurrentHashMap<Long, String>();

	public void start() {
		long index = 0;
		long total = 0;
		long count = 0;
		Long itemId = null;
		Long shopId = null;
		String sessionKey = null;

		logger.warn(new StringBuilder("Promotion start task start, at:")
				.append(new Date()));

		PromotionQueryModel queryModel = PromotionQueryModel.buildQueryModel(
				null, PromotionStatusEnum.PROMOTION_STATUS_NOT_START.value(),
				null, null, 1L, BaseQueryModel.MAX_PAGE_SIZE);
		ResultModel<PromotionDO> resultModel = itemManager
				.getPromotionList(queryModel);
		total = resultModel.getTotalItem();

		List<PromotionDO> promotionList = resultModel.getItemList();
		while (index < total) {
			for (PromotionDO promotion : promotionList) {
				itemId = promotion.getGoodsId();
				shopId = promotion.getShopId();
				sessionKey = _get_session_key_(shopId);
				// 是否可以启动了
				if (promotion.getStartTime().after(new Date())) {
					count++;
					logger.warn(new StringBuilder(
							"Find one promotion need to be started:")
							.append("id=").append(promotion.getId())
							.append(",title=").append(promotion.getTitle())
							.append(",startTime=")
							.append(promotion.getStartTime())
							.append(",endTime=").append(promotion.getEndTime()));
					promotion
							.setStatus(PromotionStatusEnum.PROMOTION_STATUS_STARTED
									.value());
					itemManager.updatePromotion(sessionKey, promotion, true);
				}
			}

			index += promotionList.size();

			queryModel.setCurrentPage(queryModel.getCurrentPage() + 1);
			resultModel = itemManager.getPromotionList(queryModel);
		}

		logger.warn(new StringBuilder("Promotion start task end, at:")
				.append(new Date()).append(", started ").append(count)
				.append(" promotion"));
	}

	public void end() {
		long index = 0;
		long total = 0;
		long count = 0;
		Long itemId = null;
		Long shopId = null;
		String sessionKey = null;

		logger.warn(new StringBuilder("Promotion end task start, at:")
				.append(new Date()));

		PromotionQueryModel queryModel = PromotionQueryModel.buildQueryModel(
				null, PromotionStatusEnum.PROMOTION_STATUS_STARTED.value(),
				null, null, 1L, BaseQueryModel.MAX_PAGE_SIZE);
		ResultModel<PromotionDO> resultModel = itemManager
				.getPromotionList(queryModel);
		total = resultModel.getTotalItem();

		List<PromotionDO> promotionList = resultModel.getItemList();
		while (index < total) {
			for (PromotionDO promotion : promotionList) {
				itemId = promotion.getGoodsId();
				shopId = promotion.getShopId();
				sessionKey = _get_session_key_(shopId);
				// 到期了
				if (promotion.getEndTime().before(new Date())) {
					count++;
					logger.warn(new StringBuilder(
							"Find one promotion need to be ended:")
							.append("id=").append(promotion.getId())
							.append(",title=").append(promotion.getTitle())
							.append(",startTime=")
							.append(promotion.getStartTime())
							.append(",endTime=").append(promotion.getEndTime()));
					promotion
							.setStatus(PromotionStatusEnum.PROMOTION_STATUS_END
									.value());
					itemManager.updatePromotion(sessionKey, promotion, false);
				}
			}

			index += promotionList.size();

			queryModel.setCurrentPage(queryModel.getCurrentPage() + 1);
			resultModel = itemManager.getPromotionList(queryModel);
		}

		logger.warn(new StringBuilder("Promotion end task end, at:")
				.append(new Date()).append(", ended ").append(count)
				.append(" promotion"));
	}

	private String _get_session_key_(Long shopId) {
		String sessionKey = sessionKeyCache.get(shopId);
		if (sessionKey == null) {
			ShopDO shop = shopManager.getByShopId(shopId);

			sessionKey = shop.getSessionKey();

			sessionKeyCache.put(shopId, sessionKey);
		}

		return sessionKey;
	}

	public void setItemManager(ItemManager itemManager) {
		this.itemManager = itemManager;
	}

	public void setShopManager(ShopManager shopManager) {
		this.shopManager = shopManager;
	}
}
